package com.personnel.service.impl;

import com.personnel.common.MessageConstant;
import com.personnel.common.Result;
import com.personnel.common.StatusCode;
import com.personnel.mapper.StaffMapper;
import com.personnel.pojo.Staff;
import com.personnel.service.StaffService;
import com.personnel.sms.SendSms;
import com.personnel.util.FileUtil;
import com.personnel.util.HttpUtil;
import com.personnel.util.MD5Util;
import com.personnel.util.RandomUtil;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 员工基本信息表(Staff)表服务实现类
 *
 * @author yuepeng
 * @since 2021-12-28 13:55:41
 * @version 1.0
 */
@Service("staffService")
public class StaffServiceImpl implements StaffService {
    @Resource
    private StaffMapper staffMapper;

    /**
     * 根据模糊条件查询总个数
     *
     * @param staffName 查询条件
     * @param departmentId 查询条件
     * @return 返回查询到的总个数
     */
    @Override
    public Map<String, Object> selectForCount(String staffName,int departmentId, String category) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", this.staffMapper.selectForCount(staffName, departmentId, category));
        return map;
    }

    /**
     * 查询所有数据
     * @return  返回所有数据
     */
    @Override
    public Result selectAll() {
        return new Result(true,
                            0,
                             MessageConstant.SEARCH_SUCCESS,
                                this.staffMapper.selectAll());
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Map<String, Object> selectById(String id) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "查询成功");
        map.put("data", this.staffMapper.selectById(id));
        return map;
    }

    /**
     * 查询分页数据
     *
     * @param index 查询起始位置
     * @param staffName  查询条件
     * @param limit  每页条数
     * @return 对象列表
     */
    @Override
    public Map<String, Object> selectForPage(int index, int limit, String staffName, Integer departmentId,  String category) {
        // 获取当前表中的总记录
        int tableCount = this.staffMapper.selectForCount(staffName,departmentId, category);
        // 总页码计算   (总条数 - 1) / 每页显示条数  + 1
        // (100 - 1) / 10 + 1 = 10        (101 - 1) / 10 + 1 = 11      (99 - 1) / 10 + 1 = 10
        int pageCount = (tableCount - 1) / 10 + 1;
        // 计算每页开始的下标值
        index = (index - 1) * 10;
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 0);
        resultMap.put("msg", "员工分页数据查询成功！");
        resultMap.put("pageCount", pageCount);  // 查询的记录总页码
        resultMap.put("count", tableCount);     // 当前表中的总条数
        resultMap.put("data", this.staffMapper.selectForPage( index, limit, staffName, departmentId, category));
        return resultMap;
    }

    /**
     * 新增数据
     *
     * @param staff 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public Result insert(Staff staff) {
        staff.setPassword(MD5Util.getMD5String(staff.getPassword()));
        this.staffMapper.insert(staff);
        return new Result(true,StatusCode.OK,MessageConstant.ADD_SUCCESS);
    }

    /**
     * 通过ID查询单条数据
     *
     * @param staff 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public Result updateById(Staff staff) {
        if (staff.getPassword() != null){
            staff.setPassword(MD5Util.getMD5String(staff.getPassword()));
        }
        this.staffMapper.updateById(staff);
        if(staff.getStaffId() == null){
            System.err.println("======================================");
            return new Result(false, StatusCode.ERROR, MessageConstant.SYSTEM_BUSY);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "更新成功");
        return new Result(true, StatusCode.OK, MessageConstant.UPDATE_SUCCESS);

    }

    @Override
    @Transactional
    public Result updateSettingById(Staff staff, HttpSession session) {
        this.staffMapper.updateById(staff);
        Staff returnStaff = this.staffMapper.selectById(String.valueOf(staff.getStaffId()));
        session.removeAttribute("user");
        session.setAttribute("user", returnStaff);
        if(staff.getStaffId() == null){
            return new Result(false, StatusCode.ERROR, MessageConstant.SYSTEM_BUSY);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "更新成功");
        return new Result(true, StatusCode.OK, MessageConstant.UPDATE_SUCCESS);

    }

    @Override
    @Transactional
    public Map<String,Object> updatePasswordById(String oldPassword,String newPassword,String staffId) {
        Map<String, Object> map = new HashMap<>();
        String md5OldPassword = MD5Util.getMD5String(oldPassword);
        Staff oldStaff = this.staffMapper.selectById(staffId);
        if(!oldStaff.getPassword().equals(md5OldPassword)){
            map.put("code", 501);
            map.put("msg", "旧密码错误！");
            return map;
        }
        Staff staff = new Staff();
        staff.setPassword(MD5Util.getMD5String(newPassword));
        staff.setStaffId(Integer.valueOf(staffId));
        this.staffMapper.updateById(staff);
        map.put("code", 200);
        map.put("msg", "修改密码成功");
        return map;
    }

    @Override
    @Transactional
    public Map<String,Object> updatePasswordByUuid(String uuid,String newPassword) {
        Map<String, Object> map = new HashMap<>();
        Staff returnStaff = this.staffMapper.selectByUuid(uuid);
        if (returnStaff != null) {
            Staff staff = new Staff();
            staff.setPassword(MD5Util.getMD5String(newPassword));
            staff.setUuid(uuid);
            this.staffMapper.updatePasswordByUuid(staff);
            map.put("code", 200);
            map.put("msg", "修改密码成功");
        }else {
            map.put("code", 500);
            map.put("msg", "验证码不正确！");
        }
        return map;
    }

    /**
     * 通过主键删除数据
     *
     * @param staffId 主键
     * @return 是否成功
     */
    @Override
    @Transactional
    public Map<String, Object> deleteById(String staffId) {
        this.staffMapper.deleteById(staffId);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "删除成功");
        return map;
    }
    @Transactional
    public Map<String, Object> upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String headImg = FileUtil.fileUpLoad(file, "uploadImg", request);
        Staff staff = (Staff)request.getSession().getAttribute("user");
        System.out.println(staff);
        this.staffMapper.updateHeadImgById(headImg,staff.getStaffId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "上传成功");
        map.put("data", headImg);
        return map;
    }
    @Transactional
    public Map<String, Object> insertHeadImg(MultipartFile file, HttpServletRequest request) throws IOException {
        String headImg = FileUtil.fileUpLoad(file, "uploadImg", request);
        HashMap<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "上传成功");
        map.put("data", headImg);
        return map;
    }

    @Override
    public List<Staff> selectForDepartment() {
        return this.staffMapper.selectForDepartment();
    }

    @Override
    @Transactional
    public Map<String, Object> sendCode(String phone){
        RandomUtil randomUtil = new RandomUtil();
        String msgCode = randomUtil.getFourRandom();
        Map<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("code", 500);
        objectObjectHashMap.put("msg", "发送失败");
        Staff staff = this.staffMapper.selectByPhone(phone);
        if (staff == null) {
            objectObjectHashMap.put("msg", "该手机号未绑定！");
            return objectObjectHashMap;
        }
        try {
            SendSms sendSms = new SendSms();
            String result = sendSms.sendMsg(phone,msgCode);
            JSONObject jsonObject = new JSONObject(result);
            // 解析返回的json对象，判断是否发送成功，如果发送成功，则更新当前用户表中的验证码内容
            // Code为OK时，代表发送成功
            Object sendStatusSet = jsonObject.get("SendStatusSet");
            JSONArray jsonArray = new JSONArray(sendStatusSet.toString());
            Object code = jsonArray.getJSONObject(0).get("Code");
            if("Ok".equals(code)) {   // 四个0的字符串代表成功，如果成功，更新数据库用户验证码字段
                staffMapper.updateByPhone("" + msgCode,
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
                        phone);
                objectObjectHashMap.put("code", 200);
                objectObjectHashMap.put("msg", "发送成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objectObjectHashMap;
    }

    @Override
    @Transactional
    public Map<String, Object> deleteByIds(String ids) {
        String[] idArray = ids.split(",");
        List<String> list = new ArrayList<>();
        list.addAll(Arrays.asList(idArray));
        this.staffMapper.deleteByIds(list);
        Map<String, Object> map = new HashMap<>();
        map.put("code", 200);
        map.put("msg", "删除成功");
        return map;
    }
}